package com.dome.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * springboot集成mybatis的基本入口 1）创建数据源(如果采用的是默认的tomcat-jdbc数据源，则不需要)
 * 2）创建SqlSessionFactory 3）配置事务管理器，除非需要使用事务，否则不用配置
 */
@Configuration // 该注解类似于spring配置文件
public class MyBatisConfig implements EnvironmentAware {

    private Environment environment;
    static  Map<Object, Object>  targetDataSources = new HashMap<Object, Object>();


    @Bean
    @Primary
    @Scope("singleton")
    public DynamicDataSource dataSource() throws Exception {
    	Properties props=new Properties();
		RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
		//加载主数据源
        DataSource ds = DruidDataSourceFactory.createDataSource(this.addProperties(propertyResolver, props));
        targetDataSources.put("ds", ds);

        propertyResolver = new RelaxedPropertyResolver(environment, "custom.datasource.");
        String[] names= propertyResolver.getProperty("names").split(",");
        for (int i = 0; i <names.length; i++) {
            propertyResolver = new RelaxedPropertyResolver(environment, "custom.datasource."+names[i]+".");
            DataSource dsmay= DruidDataSourceFactory.createDataSource(this.addProperties(propertyResolver,props));
        	targetDataSources.put(names[i],dsmay);
		}

        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
        dataSource.setDefaultTargetDataSource(ds);// 默认的datasource设置为test2DataSource
        return dataSource;
    }
    public   Properties   addProperties(RelaxedPropertyResolver propertyResolver, Properties props){
         props.put("driverClassName", propertyResolver.getProperty("driverClassName"));
         props.put("url", propertyResolver.getProperty("url"));
         props.put("username", propertyResolver.getProperty("username"));
         props.put("password", propertyResolver.getProperty("password"));
         System.err.println("你好我是数据源"+propertyResolver.getProperty("url"));
		return props;
    }

    /**
     * 根据数据源创建SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {
    	SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
    	sessionFactoryBean.setDataSource(ds);

        //映射实体包
        sessionFactoryBean.setTypeAliasesPackage("com.dome.model");
        //映射mapper文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        sessionFactoryBean.setConfiguration(mybatisSetting());



        return sessionFactoryBean.getObject();
    }

    @Bean
    public org.apache.ibatis.session.Configuration mybatisSetting(){
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        return  configuration;
    }

    /**
     * 配置事务管理器
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }
	@Override
	public void setEnvironment(Environment environment) {
	        this.environment = environment;
	}


}